package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.entity.SysRole;
import com.example.demo.entity.SysUser;
import com.example.demo.entity.TbMenu;
import com.example.demo.service.SysRoleService;
import com.example.demo.service.SysUserService;
import com.example.demo.service.impl.TokenService;
import com.example.demo.utils.MD5Sreat;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 * @className wuyp
 * @description:
 * @Date 2022/3/24 17:31
 **/
@Controller
public class UserController {
    @Autowired
    private SysRoleService roleService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private TokenService tokenService;
    private  ModelAndView mv;
    private  List<Integer>idList;
    private   JSONArray jsonArray;
    private  List<SysRole>hasRoles;

    @RequestMapping({"/index", "/"})
    public String index(){
        return "login";
    }

    @RequestMapping(value = "/getToken")
    @ResponseBody
    public JSONObject getToken(@RequestBody Map mp){
       /* System.out.println("userrname=="+(mp.get("username").toString()));*/
        //增加token认证
        JSONObject jsonObject=new JSONObject();
        SysUser user=sysUserService.getUser(mp.get("username").toString(),
                MD5Sreat.jiami(mp.get("username").toString(),mp.get("password").toString()).toString());
        String pwd =MD5Sreat.jiami(mp.get("username").toString(),mp.get("password").toString()).toString();
        if(user==null){
            jsonObject.put("msg","用户名或者密码错误，请重新输入!!");
              return jsonObject;
        }else {
            String jwt_token = tokenService.getToken(user);
            jsonObject.put("token", jwt_token);
            jsonObject.put("user", user);
             return jsonObject;
        }
    }

    /**
     * 登录页面
     * @param username
     * @param password
     * @param request
     * @return
     */
    @RequestMapping(value = "/login")
    public String login(String username, String password, HttpServletRequest request){
        System.out.println("userMap===="+username);
        System.out.println("token===="+ request.getParameter("token"));
        request.getParameter("token");
        //1.获取subject
        Subject subject = SecurityUtils.getSubject();
        //2.封装用户数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            //3.执行登陆方法
            subject.login(token);
            //登陆成功
            return "redirect:indexPage";
        } catch (UnknownAccountException e) {
            //e.printStackTrace();
          /*  model.addAttribute("msg","登陆失败：用户名不存在");*/
            //登陆失败：用户名不存在
            return "login";
        } catch (IncorrectCredentialsException e) {
            //e.printStackTrace();
            /*model.addAttribute("msg","登陆失败：用户名不存在");*/
            //登陆失败：用户名不存在
            return "login";
        }
    }

    /**
     * 主页面
     * @return
     */
    @RequestMapping(value = "/indexPage")
    public String indexPage(){
        System.out.println("obj=="+SecurityUtils.getSubject().getPrincipal().toString());
        SysUser user =sysUserService.findByUsername(SecurityUtils.getSubject().getPrincipal().toString());
        //登陆成功后，输出对应的角色和菜单
        for(SysRole role: user.getRoles()){
            System.out.println(role.getName()+"=====角色");
            for(SysRole roles : role.getChildren()){
                System.out.println(roles.getName()+"===="+role.getName()+"角色对应的菜单");
//                for(TbMenu menus:role.getMenus()){
//                    System.out.println("菜单权限===="+menus.getName());
//                }
            }
        }
        return "indexPage";
    }
    @RequestMapping("/userList")
    public  String  userList(Model model){
        List<SysUser>userList =sysUserService.findAll();
        model.addAttribute("userList",userList);
        return "/views/userList";
    }

    /**
     * 删除用户信息
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/deleteUser")
    public  String  deleteUser(@RequestParam("id")Integer id, Model model){
        sysUserService.deleteUserById(id);
        return "redirect:/userList";
    }

    /**
     * 批量删除用户信息
     * @param ids
     * @param model
     * @return
     */
    @RequestMapping("/deleteBatchUser")
    public  String  deleteBatchUser(@RequestParam("ids") String ids, Model model){
        idList =new ArrayList<Integer>();
        jsonArray = JSON.parseArray(ids);
        System.out.println("ids===="+jsonArray);
        for (int i=0;i<jsonArray.size();i++){
            idList.add(Integer.parseInt(jsonArray.get(i).toString()));
        }
       sysUserService.deleteBatchUsers(idList);
        return "redirect:/userList";
    }
    @RequestMapping("/openUser")
    public  String  openUser(Model model){
        List<SysRole>sysRolses =roleService.findAll();
        model.addAttribute("sysRolses",sysRolses);
        return "/views/user_add";
    }

    @RequestMapping("/openEdit")
    public  String  openEdit(@RequestParam("id")Integer id,Model model){
         SysUser user =sysUserService.findById(id);
         StringBuffer stringBuffer =new StringBuffer();
         //遍历角色
         for(SysRole role :user.getRoles()){
            stringBuffer.append(role.getId());
         }
         System.out.println("user=="+user.toString());
        List<SysRole>sysRolses =roleService.findAll();
        model.addAttribute("sysRolses",sysRolses);
        model.addAttribute("user",user);
        model.addAttribute("hasRoles",stringBuffer.toString());

        return "/views/user_edit";
    }

    @RequestMapping("/editUser")
    public  String  editUser(HttpServletRequest request,SysUser user,Model model){
        System.out.println("user==="+user.toString());
        user.setPassword(MD5Sreat.jiami(user.getUsername(),user.getPassword()).toString());
        String[] crowd =request.getParameterValues("roleId");
        List<Integer> ids =new ArrayList<Integer>();
        //添加角色信息
        for (String id :crowd){
            ids.add(Integer.parseInt(id));
        }
        //查找所有角色
        List<SysRole> roles = roleService.findAllById(ids);
        user.setRoles(roles);
        System.out.println("roles==="+roles.size());
        sysUserService.updateUserById(user);
        return "redirect:/userList";
    }
    @RequestMapping("/addUser")
    public  String  addUser(HttpServletRequest request, Model model){
        String username =request.getParameter("username");
        String password =request.getParameter("password");
        String name =request.getParameter("name");
        password= MD5Sreat.jiami(username,password).toString();
        //用户实体
        SysUser user=new SysUser();
        user.setName(name);
        user.setUsername(username);
        user.setPassword(password);
        String[] crowd =request.getParameterValues("roleId");
        List<Integer> ids =new ArrayList<Integer>();
        //添加角色信息
        for (String id :crowd){
            ids.add(Integer.parseInt(id));
        }
        //查找所有角色
        List<SysRole> roles = roleService.findAllById(ids);
        user.setRoles(roles);
        SysUser uu=sysUserService.findByUsername(username);
        if(null!=uu){
        }else{
            sysUserService.addUser(user);
        }
        return "redirect:/userList";
    }
    /**
     * 退出登录
     * @return
     */
    @RequestMapping("/logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
            subject.logout();
        }
        return "redirect:/indexPage";
    }

    @RequestMapping("/unAuth")
    public String unAuth(){
        return "unAuth";
    }

    @RequestMapping("/system")
    public String system(){
        return "system";
    }

    @RequestMapping("/user")
    public String user(){
        return "user";
    }
}
